//主控制器 ===========================================================
var MainCtrl = [
   '$route', '$rootScope', '$scope', '$location', '$window', '$interval', 'messageGet', 'messageRead', 'saveUserReadMessage', 'BaseGoods', 'ngDialog', 'ReceiptRecord', 'Language', 'shopCashDesk', 'ShopSetCheck', 'timeStamp2String', 'shortCutAction', 'ShopAttend','ThirdDev','waitUpLoad',
    function (
            $route,$rootScope, $scope, $location, $window, $interval,
            messageGet, messageRead, saveUserReadMessage, BaseGoods, ngDialog,
            ReceiptRecord, Language, shopCashDesk, ShopSetCheck,
            timeStamp2String, shortCutAction, ShopAttend,ThirdDev,waitUpLoad) {

//        const BrowserWindow = nodeRequire('electron').remote.BrowserWindow;
//        BrowserWindow.getFocusedWindow().webContents.openDevTools();

        $rootScope.current_shop = $api.getStorage('current_shop') ? $api.getStorage('current_shop') : '';
        $rootScope.language = {};
        $rootScope.is_pc = isPC; //angular全局判断是否为PC版本p
        Language().then(function (ret) {
            $rootScope.language = ret.data;
        });
        var window_id = 0;
        var result = {};
        //同步结果
        //弹框ID标识
        $scope.news_select_data = [];
        //消息选择器弹框的数据
        //退出程序
        $scope.exit = function () {
            baison_app.api.toLauncher();
        };
        $scope.todo = function () {
            baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],
                title: $rootScope.language.COMMON_TITLE_HINT,
                msg: $rootScope.language.TIP_INDEX_TODO_MESSAGE
            });
        };
        //扫描枪输入监听事件，需要在监听的控制器内重载$rootScope.saomiao方法
        $rootScope.$on('$routeChangeStart', function (evt, next, current) {
            $rootScope.saomiao = function (event) {};
        });
        //会员列表
        //$rootScope.curr = '';
        //$rootScope.reback = 0;
        //返回到上一页
        $scope.back = function () {
            if($route.current.$$route.originalPath == "/cashier/settle"){ //结算界面
                var length = $rootScope.goods_cart.checklist.length;
                for (var i = 0; i < length; i++) {
                    if (is_del_pay_log(i) == 1) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_COMPLETE_THE_PAY}); //'请完成支付'
                        return;
                    }
                }
            }
            $window.history.back();
        };
        //检查是否可以删除消费记录 （支付宝与微信不可删除）
        var is_del_pay_log = function (i) {
            if (($rootScope.goods_cart.checklist[i].coupon_code != '' && $rootScope.goods_cart.checklist[i].code != '004') || $rootScope.goods_cart.checklist[i].code == '003') {
                return 1;
            } else {
                return 0;
            }
        };
        //返回到首页
        $scope.home = function () {
            if($route.current.$$route.originalPath == "/cashier/settle"){ //结算界面
                var length = $rootScope.goods_cart.checklist.length;
                for (var i = 0; i < length; i++) {
                    if (is_del_pay_log(i) == 1) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_PLZ_COMPLETE_THE_PAY}); //'请完成支付'
                        return;
                    }
                }
            }
            if ($location.$$path != '/login') {
                $location.path('/index');
            }
        };
        var relogin_window = '';
        //切换收银员
        $scope.reLogin = function () {
            relogin_window = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/relogin.html',
                disableAnimation: true,
                scope: $scope,
            });
        };
        //关闭对话框
        $scope.relogin_close = function () {
            ngDialog.close(relogin_window);
        };
        //切换登录页面
        $scope.relogin_submit = function () {
            ngDialog.close(relogin_window);
            $location.path('/login');
        };
//      $scope.reLogin = function () {
//          baison_app.api.confirm({
//              title: $rootScope.language.TIP_CASHIER_TITLE,
//              msg: $rootScope.language.TIP_INDEX_CHANGE_USER,
//              buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON, $rootScope.language.ACT_CANCEL]
//          }, function (ret, err) {
//              if (ret.buttonIndex == 1) {
//                  $rootScope.user = {};
//                  $location.path('/login');
//              } else if (ret.buttonIndex == 2) {
//                  return false;
//              }
//          });
//      };
        //光标定位到输入框，或者某个特定的输入框，默认为收银主输入框
        $scope.focus = function (objID) {
            setTimeout(function () {
                if (typeof objID == 'undefined' || objID == '') {
                    var setKeyboard = document.getElementById("inputDesk");
                } else {
                    var setKeyboard = document.getElementById(objID);
                }
                setKeyboard.focus();
            }, 50);
        };
        //消息页面：服务器下载消息
        $rootScope.newsInterval = true;
        $interval(function () {
            if (typeof $rootScope.current_shop == 'undefined' || $rootScope.current_shop == '') {
                //未绑定店铺
                return;
            }
            if (typeof $rootScope.user == 'undefined' || $rootScope.user == '') {
                //未登录
                return;
            }

            //loading页面，登录页面，不去下载消息
            var url = $location.url();
            if (url == '/login' || url == '/hello') {
                return;
            }
            if ($rootScope.newsInterval) {
                //从服务器下载数据  
                messageGet().then(function (ret) {
                    //baison_app.api.alert({msg:ret,title:'get'});
                    messageRead().then(function (ret) {
                        //baison_app.api.alert({msg:ret,title:'read'});
                        if (ret.length > 0) {
                            $scope.news_select_data = ret;
                            baison_app.api.toast({
                                msg: ret.length + $rootScope.language.TIP_INDEX_UNREAD_MESSAGE
                            });
                            window_id = ngDialog.open({closeByDocument: false,
                                template: './html/message/un_read.html',
                                scope: $scope,
                                disableAnimation: true,
                                trapFocus: false,
                                preCloseCallback: function () {
                                    $rootScope.newsInterval = true;
                                    return true;
                                }
                            });
                            $rootScope.newsInterval = false;
                        } else {
                            baison_app.api.toast({
                                msg: $rootScope.language.TIP_INDEX_NO_UNREAD_MESSAGE
                            });
                            $rootScope.newsInterval = false;
                        }
                    });
                }).catch(function (err) {
                    //baison_app.api.toast({msg : err});
                    //TODO 记录日志
                });
            }

        }, 180000);
		
		var configData = $api.getStorage('configData');
		//同步时间
        //离线数据自动上传  会员和小票
        $interval(function () {
            var configData = $api.getStorage('configData');
            if (configData.auto_load == 0) {
                //检查是否有数据上传
                var check_right_upload_data = function (list) {
                    if (list.length == 0) {
                        return 0;
                    }
                    for (var i = 0; i < list.length; i++) {
                        var re = /fail/;
                        if (!re.test(list[i].comment)) {
                            return 1;
                        }
                    }
                    return 0;
                };
                //上传离线数据
                var btn_receipt_upload = function () {
                    var receipt_data = $scope.receipt_list;
                    waitUpLoad.receipt_record_loacl_to_api(receipt_data).then(function (ret) {
                    });
                };
                var btn_vip_upload = function () {
                    var vip_data = $scope.vip_list;
                    waitUpLoad.vip_loacl_to_api(vip_data).then(function (ret) {
                    });
                };
                //获取未上传数据 receipt
				if(configData.offline_receipt){
					waitUpLoad.receipt_record_get_wait_upload_group_list().then(function (data) {
						if (data != undefined && data != null) {
							$scope.receipt_list = data;
							if (check_right_upload_data($scope.receipt_list) == 0) {
								return;
							} else {
								btn_receipt_upload();
							}
						}
					});
				}
                //获取未上传数据 vip
				if(configData.offline_vip){
					waitUpLoad.vip_get_wait_upload_group_list().then(function (data) {
						if (data != undefined && data != null) {
							$scope.vip_list = data;
							if (check_right_upload_data($scope.vip_list) == 0) {
								return;
							} else {
								btn_vip_upload();
							}
						}
					});
				}
                
            }
//        }, 5000);
        }, configData.load_frequency);
		
		
		
        //库存更新
        $rootScope.SkuNumInterval = true;
        var time;
        //同步时间
        var configData = $api.getStorage('configData');
        if (configData == undefined || configData.hasOwnProperty('frequency') == false) {
            time = 43200000;
        } else {
            switch (configData.frequency) {
                case "1":
                    time = 1800000;
                    break;
                case "2":
                    time = 3600000;
                    break;
                case "3":
                    time = 21600000;
                    break;
                case "4":
                    time = 43200000;
                    break;
                case "5":
                    time = 86400000;
                    break;
                default:
                    time = 1800000;
                    break;
            }
        }
        $interval(function () {
            var configData = $api.getStorage('configData');
            if (configData.is_syn == "1" || configData.frequency == '') {
                return;
            }
            if (typeof $rootScope.current_shop == 'undefined' || $rootScope.current_shop == '') {
                //未绑定店铺
                return;
            }
            if (typeof $rootScope.user == 'undefined' || $rootScope.user == '') {
                //未登录
                return;
            }
            //loading页面，登录页面，不去更新库存
            var url = $location.url();
            if (url == '/login' || url == '/hello') {
                return;
            }
            //库存开始更新提示
            baison_app.api.toast({
                msg: $rootScope.language.TIP_INDEX_START_INVENTORY
            });
            //判断本地是否有已支付未上传的小票
            ReceiptRecord.get_list_local_not_upload().then(function (ret) {
                if (Object.keys(ret).length == 0 || ret.length == '') {
                    //没有未上传的小票
                    if ($rootScope.SkuNumInterval) {
                        //lite使用
                        if (!ThirdDev.is_lqx()) {//$rootScope.purview['\/setting\/SkuNum_syn'].show == 1
                            $scope.is_all = 0;
                            BaseGoods.getSkuNum_by_store_code($scope.is_all).then(function (response) {
                                if (response == false) {
                                    baison_app.api.toast({
                                        msg: $rootScope.language.TIP_INDEX_NO_INVENTORY
                                    });
                                    result = {
                                        'syn': 1, //表示同步失败
                                        'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                        'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                        'time': timeStamp2String(new Date(), 'datetime'),
                                        'result': 1, //1表示失败
                                        'reason': $rootScope.language.TIP_INDEX_NO_INVENTORY
                                    };
                                    setKuCun_syn(result);
                                    $rootScope.SkuNumInterval = false;
                                } else {
                                    //库存更新成功
                                    baison_app.api.toast({
                                        msg: $rootScope.language.TIP_INDEX_THRER_INVENTORY
                                    });
                                    result = {
                                        'syn': 0, //表示成功
                                        'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                        'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                        'time': timeStamp2String(new Date(), 'datetime'),
                                        'result': 0,
                                        'reason': $rootScope.language.TIPS_CASHIER_NOT_AVAILABLE
                                    };
                                    setKuCun_syn(result);
                                    $rootScope.SkuNumInterval = false;
                                }
                            });
                        } else {
                            //林清轩使用
                            var length = 200;
                            //从服务器下载库存到本地
                            BaseGoods.getAllSkus(0, length).then(function (response) {
                                if (Object.keys(response).length < 1) {
                                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],
                                        title: $rootScope.language.COMMON_TITLE_HINT,
                                        msg: $rootScope.language.TIP_INDEX_NO_GOODS
                                    });
                                    return;
                                }
                                //更新本地
                                BaseGoods.getSkuNum_by_api_skus(response).then(function (res) {
                                    if (res == false) {
                                        baison_app.api.toast({
                                            msg: $rootScope.language.TIP_INDEX_THRER_INVENTORY
                                        });
                                        result = {
                                            'syn': 1, //表示同步失败
                                            'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                            'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                            'time': timeStamp2String(new Date(), 'datetime'),
                                            'result': 1, //1表示失败
                                            'reason': $rootScope.language.TIP_INDEX_NO_INVENTORY
                                        };
                                        setKuCun_syn(result);
                                        $rootScope.SkuNumInterval = false;
                                    } else {
                                        var n = 200;
                                        function CycleSyn(n) {
                                            BaseGoods.getAllSkus(n, 200).then(function (response) {
                                                if (Object.keys(response).length > 0) {
                                                    BaseGoods.getSkuNum_by_api_skus(response).then(function (ret) {
                                                        if (ret != false) {
                                                            length = n + 200;
                                                            return CycleSyn(length);
                                                        } else {
                                                            //库存失败
                                                            baison_app.api.toast({
                                                                msg: $rootScope.language.TIP_INDEX_THRER_INVENTORY_FAIL
                                                            });
                                                            result = {
                                                                'syn': 1, //表示同步失败
                                                                'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                                                'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                                                'time': timeStamp2String(new Date(), 'datetime'),
                                                                'result': 1, //1表示失败
                                                                'reason': $rootScope.language.TIP_INDEX_NO_INVENTORY
                                                            };
                                                            setKuCun_syn(result);
                                                            $rootScope.SkuNumInterval = false;
                                                        }
                                                    });
                                                } else {
                                                    //库存更新成功
                                                    baison_app.api.toast({
                                                        msg: $rootScope.language.TIP_INDEX_THRER_INVENTORY
                                                    });
                                                    result = {
                                                        'syn': 0, //表示成功
                                                        'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                                        'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                                        'time': timeStamp2String(new Date(), 'datetime'),
                                                        'result': 0,
                                                        'reason': $rootScope.language.TIPS_SET_NOTHING
                                                    };
                                                    setKuCun_syn(result);
                                                }
                                            });
                                        }
                                        ;
                                        CycleSyn(n);
                                    }
                                }).catch(function (err) {
                                    baison_app.api.toast({
                                        msg: err
                                    });
                                    $rootScope.SkuNumInterval = false;
                                });
                            }).catch(function (err) {
                                baison_app.api.toast({
                                    msg: err
                                });
                                result = {
                                    'syn': 1, //表示同步失败
                                    'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                    'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
                                    'time': timeStamp2String(new Date(), 'datetime'),
                                    'result': 1, //1表示失败
                                    'reason': $rootScope.language.TIP_INDEX_SEARCH_TYPE
                                };
                                setKuCun_syn(result);
                                $rootScope.SkuNumInterval = false;
                            });
                        }
                    }
                } else {
                    baison_app.api.toast({
                        msg: $rootScope.language.TIP_INDEX_NO_INVENTORY
                    });
                    result = {
                        'syn': 1,
                        'sku': $rootScope.language.TIPS_INVENTORY_TOTAL,
                        'name': $rootScope.language.TIPS_INVENTORY_TOTAL,
                        'time': timeStamp2String(new Date(), 'datetime'),
                        'result': 1,
                        'reason': $rootScope.language.TIP_INDEX_NOT_UPLOAD_RECEIPT
                    };
                    setKuCun_syn(result);
                }
            });
        }, time);
        var setKuCun_syn = function (result) {
            var results = $api.getStorage('stock') ? $api.getStorage('stock') : [];
            results.push(result);
            $api.setStorage('stock', results);
        };
        //商品价格同步 **************************************************************
        var sku_price_syn = function () {
            var time;
            //同步时间
            var configData = $api.getStorage('configData');
            switch (configData.skuPriceSynch.frequency) {
                case "1":
                    time = 1800000;
                    break;
                case "2":
                    time = 3600000;
                    break;
                case "3":
                    time = 21600000;
                    break;
                case "4":
                    time = 43200000;
                    break;
                case "5":
                    time = 86400000;
                    break;
                default:
                    time = 1800000;
                    break;
            }
            //time = 1000;
            $interval(function () {
                var configData = $api.getStorage('configData');
                if (!$rootScope.SkuPriceInterval) {
                    return;
                }
                if (configData.skuPriceSynch.is_syn == "1" || configData.skuPriceSynch.frequency == '') {
                    return;
                }
                if (typeof $rootScope.current_shop == 'undefined' || $rootScope.current_shop == '') {
                    //未绑定店铺
                    return;
                }
                if (typeof $rootScope.user == 'undefined' || $rootScope.user == '') {
                    //未登录
                    return;
                }
                //loading页面，登录页面，不去更新库存
                var url = $location.url();
                if (url == '/login' || url == '/hello') {
                    return;
                }
                $scope.$broadcast('skuPrcie', 'ok');
            }, time);
        };
        $rootScope.SkuPriceInterval = false;
        $scope.$on('no_skuPrcie', function (event, data) {
            $rootScope.SkuPriceInterval = false;
        });
        // 权限检查
        //url_check:要检查权限URL        //url_change跳转URL
        $rootScope.purviewCheckChange = function (url_check, url_change) {
            if (!$rootScope.purview[url_check]) {
                $location.path(url_change);
                //baison_app.api.toast({msg: $rootScope.language.'此权限尚未定义，请联系管理员'});
            } else if ($rootScope.purview[url_check].show == 0) {
                if (url_change) {
                    $location.path(url_change);
                }
                //baison_app.api.toast({msg: $rootScope.language.'您无' + $rootScope.purview[url_check].name + '的操作权限'});
                return 1;
            }
        };
        $scope.cash_modify = function () {
            $location.path('/cashier/index');
        };
        //营业时间设置
        $scope.startTime = function () {
            $scope.cashDate = new Date();
            var windows_startTime = ngDialog.open({closeByDocument: false,
                template: './html/cashier/start_cashier.html',
                disableAnimation: true,
                trapFocus: false,
                scope: $scope,
                controller: ['$scope', 'shopCashDesk',
                    function ($scope, shopCashDesk) {
                        //收银台设置
                        $scope.choseCashDesk = function () {
                            var configData = $api.getStorage('configData');
                            $scope.cashDesk = configData.cashsetData.cashNum;
                            var param = {
                                shop_code: $rootScope.current_shop.ShopCode
                            };
                            shopCashDesk.getCashList(param).then(function (ret) {
                                $scope.cashlist = ret.data.data.data;
                                if (configData.cashsetData.cashNum == '') {
                                    $scope.cashDesk = $scope.cashlist[0].cashNum;
                                } else {
                                    $scope.cashDesk = configData.cashsetData.cashNum;
                                    $rootScope.cashNum = $scope.cashDesk;
                                    configData.cashsetData.cashNum = $rootScope.cashNum;
                                }
                                $api.setStorage('configData', configData);
                            }).catch(function (err) {
                                $scope.cashDesk = configData.cashsetData.cashNum;
                                $rootScope.cashNum = $scope.cashDesk;
                                $scope.cashlist = [];
                                $scope.cashlist.push(configData.cashsetData);
                                baison_app.api.toast({
                                    msg: $rootScope.language.MSG_NETWORK_ABNORMAL
                                });
                                configData.cashsetData.cashNum = $rootScope.cashNum;
                                $api.setStorage('configData', configData);
                            });
                            $scope.cashierShow = 0;
                        };
                        //跳转到收银界面
                        $scope.cashDeskSet = function () {
                            var configData = $api.getStorage('configData');
                            configData.finished = 0;
                            configData.cashsetData.cashNum = $scope.cashDesk;
                            $api.setStorage('configData', configData);
                            ngDialog.close(windows_startTime);
                            //上传营业状态到服务器
                            var operate_time = new Date();
                            var nowTime = timeStamp2String(operate_time, 'datetime');
                            var nowCashierTime = timeStamp2String($scope.cashDate, 'date');

                            var param = {
                                cashier_time: nowCashierTime,
                                operate_time: nowTime
                            };

                            var configData = $api.getStorage('configData');
                            configData.cashierTime = nowCashierTime;
                            $api.setStorage('configData', configData);

                            ShopAttend.shop_status(param, 1);

                            $location.path('/cashier/index');
                        };
                        //营业时间设置
                        $scope.cashierTime = function () {
                            $scope.cashierShow = 1;
                        };
                        //跳转到收银台设置
                        $scope.cashierSetTime = function (cashDate) {
                            $scope.cashDate = cashDate;
                            if (typeof $scope.cashDate == 'undefined') {
                                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_INDEX_START_CASHIER});
                                return;
                            } //TODO 库位还没写
                            var configData = $api.getStorage('configData');
                            configData.cashsetData.cashDate = $scope.cashDate;
                            $api.setStorage('configData', configData);
                            $scope.choseCashDesk();
                        };
                        $scope.cashierTime();
                    }
                ]
            });
        };
        //弹框处理================================================================
        //未读消息选择
        $scope.news_select_click = function (news, index) {
            $scope.news_select_data.splice(index, 1);
            //每读完一条,状态回传给服务器()
            saveUserReadMessage(news.message_id);
            if ($scope.news_select_data == '') {
                ngDialog.close(window_id);
            }
        };
        //全局快捷键部分===========================================================
        //home返回首页
        shortCutAction.handler('', 'home', function () {
            $scope.home();
            $scope.$apply();
        });
        //帮助弹窗
        $scope.helpPtAc = false;
        $scope.help_prompt = function (prompt_cont, followid) {
            baison_app.api.helpPrompt({
                id: followid + 00,
                msg: prompt_cont,
                idfollow: followid,
            });
            $scope.helpPtAc = true;
        };
        //点击其他地方关闭弹窗
        $scope.helpPtClose = function () {
            var list = dialog.list;
            for (var i in list) {
                list[i].remove();
            }
            $scope.helpPtAc = false;
        }
    }];
//欢迎页面 ===========================================================
var HelloCtrl = ['$interval', '$rootScope', '$location', 'dbOpen', 'dbInit', 'dbVesionInit', 'appInit', 'AutoPatchDownload',
    function ($interval, $rootScope, $location, dbOpen, dbInit, dbVesionInit, appInit, AutoPatchDownload) {
        $rootScope.patch_uninstall = false;
            //版本数据库控制处理逻辑(执行一次)
            var deal_version_db = function () {
	            var _configData = $api.getStorage('configData');
                //版本号
                var version = '';
                //获取当前版本号
                var cur_version = _configData.version;
                //版本号列表
                var version_list = _configData.versionList;
                //获取当前版本号所在索引
                var index = version_list.indexOf(cur_version);
                //执行中间版本sql语句 (TODO versionList需确保正确)
                var i = index + 1;
                //baison_app.api.alert({msg:i,title:'iii'});
                var exec_version_info = function (i) {
                    version = version_list[i];
                    if (version != undefined) {
                        
                        dbVesionInit('YsPos', version).then(function () {
                            //vesion版本执行完成,设置版本号(TODO 每个sql需执行成功)
                            //set_version_configData(version);
                            _configData.version = version;
                            $api.setStorage('configData', _configData);
                            i++;
                            exec_version_info(i);
                        });
                        
                    }
                };
                exec_version_info(i);
            };
            //loading页面 延迟跳入到首页
            var timer = $interval(function () {
                if (typeof baison_app.api !== 'undefined') {
                    if(!$rootScope.is_online) {
                        var path = 'file://' + baison_app.api.fsDir + '/YsPos.db';
                        baison_app.fs.exist({
                            path: path
                        }, function (ret, err) {
                            if (!ret.exist) {
                                baison_app.fs.createFile({
                                    path: 'fs://YsPos.db'
                                }, function (ret, err) {
                                    if (ret.status) {
                                        //打开数据库执行数据库语句
                                        var configData = $api.getStorage('configData');
                                        dbOpen.openDatabase('YsPos', path).then(function(){
                                            dbInit('YsPos').then(function(ret){
                                                configData.create_db = 1;
                                                $api.setStorage('configData', configData);
                                                deal_version_db();
                                                appInit();
                                                $interval.cancel(timer);
                                                
                                                $location.path('/login');
                                                
                                            }).catch(function(err){
                                            	//baison_app.api.alert({msg:'1'});
                                            	//baison_app.api.alert({msg:err});
                                            });
                                        }).catch(function(err){
                                            	//baison_app.api.alert({msg:'2'});
                                            	//baison_app.api.alert({msg:err});
                                            });
                                    }
                                });
                            } else {
                                //打开数据库执行数据库语句
                                var configData = $api.getStorage('configData');
                                if (configData.create_db == 0) {
                                    baison_app.fs.remove({
                                        path: path
                                    }, function (ret, err) {
                                        if (ret.status) {
                                            baison_app.fs.createFile({
                                                path: 'fs://YsPos.db'
                                            }, function (ret, err) {
                                                if (ret.status) {
                                                    //打开数据库执行数据库语句
                                                    dbOpen.openDatabase('YsPos', path).then(function(){
                                                        dbInit('YsPos').then(function(){
                                                            configData.create_db = 1;
                                                			$api.setStorage('configData', configData);
                                                            deal_version_db();
                                                            appInit();
                                                            $interval.cancel(timer);
                                                            
                                                            $location.path('/login');
                                                            
                                                        }).catch(function(err){
                                            	//baison_app.api.alert({msg:'2'});
                                            	//baison_app.api.alert({msg:err});
                                            });
                                                    }).catch(function(err){
                                            	//baison_app.api.alert({msg:'4'});
                                            	//baison_app.api.alert({msg:err});
                                            });
                                                }
                                            });
                                        }
                                    });
                                } else {
                                    dbOpen.openDatabase('YsPos', path).then(function(){
                                        dbInit('YsPos').then(function(){
                                            deal_version_db();
                                            appInit();
                                            $interval.cancel(timer);
                                            //判断第二次进来
                                            
                                            $location.path('/login');
                                            
                                        }).catch(function(err){
                                            	//baison_app.api.alert({msg:'5'});
                                            	//baison_app.api.alert({msg:err});
                                            });
                                    }).catch(function(err){
                                            	//baison_app.api.alert({msg:'6'});
                                            	//baison_app.api.alert({msg:err});
                                            });
                                }
                            }
                        });
                    } else {
                    	var configData = $api.getStorage('configData');
                        configData.create_db = 1;
                        $api.setStorage('configData', configData);
                        deal_version_db();
                        $interval.cancel(timer);
                        
                        $location.path('/login');
                        
                    }
                }
            }, 500, 1);
        
        //$location.path('/login');
    }];
//首页控制器 ===========================================================
var IndexCtrl = [
    '$scope', '$rootScope', '$location', 'UserLoginCheck', 'UserSetPicture', 'dateDisplay', 'weatherDownload', 'pictureDownload', 'barcodesDownload', 'apiService', 'timeStamp2String', 'VIP', 'ruKu', 'ngDialog', 'get_api', 'shortCutAction', 'ShopSetCheck', 'checkGetList',
    function (
            $scope, $rootScope, $location, UserLoginCheck, UserSetPicture, dateDisplay,
            weatherDownload, pictureDownload, barcodesDownload, apiService, timeStamp2String,
            VIP, ruKu, ngDialog, get_api, shortCutAction, ShopSetCheck, checkGetList) {
        //登录判断
        UserLoginCheck();
        //打开外部链接 ===================================================
        $scope.configData = {};
        $scope.configData = $api.getStorage('configData');
        $scope.open_outlink = function(i){
            var outlink = $scope.configData.outlink;
            baison_app.api.openApp({
                'mimeType':'text/html',
                'uri':outlink[i].url,
                'iosUrl':outlink[i].url
            },function(){});
        };
        //首页头部导航外链
        $scope.links_box=false
        $scope.links_box_switch=function(){
            if ($scope.links_box) {
                $scope.links_box=false;
            }else{
                $scope.links_box=true;
            };
        };
        //获取当前收银员头像
        var user_head = $api.getStorage('user_head') ? $api.getStorage('user_head') : {};
        if (typeof $rootScope.user === "undefined" || typeof user_head[$rootScope.user.UserCode] === "undefined") {
            $scope.user_img = "./image/head_img_default.png";
        } else {
            $scope.user_img = user_head[$rootScope.user.UserCode];
        }

        //获取公司信息
        apiService('sys/company_info/get_info', {}).then(function (ret) {
            if (ret.data.status == 1) {
                $rootScope.company_info = ret.data.data;
            } else {
                $rootScope.company_info = {};
                $rootScope.company_info.brand_name = '';
                $rootScope.company_info.website = '';
            }
        }).catch(function (err) {
            $rootScope.company_info = {};
            $rootScope.company_info.brand_name = '';
            $rootScope.company_info.website = '';
        });
        $scope.cas_show = true;
        var configData = $api.getStorage('configData');

        //获取移动终端默认货币
        if (configData.currency_foreign == 1) {
            checkGetList.get_list().then(function (response) {
                response.currencyType.forEach(function (n) {
                    if (n.cur_code == configData.standard_coin) {
                        $rootScope.StandardRate = n.rate;
                    }
                });
            });
        } else {
            $rootScope.StandardRate = 1;
        }
        //在线类型
        $scope.connectionType = baison_app.api.connectionType;
        $scope.online = true;
        apiService('/', {}).success(function (ret) {
            $scope.online = true;
        }).catch(function (e) {
            $scope.online = false;
        });
        //天气预报语言切换
        $scope.weatherL = 'zh_CHS';

        //added by lqx maowei on 20170113当前日期
        $scope.today_date = dateDisplay();
        //if ($rootScope.language.TIPS_WEATHER_LANGUAGE == 'zh-CHS') {
        //    $scope.weatherL = 'zh_CHS';
        //} else if ($rootScope.language.TIPS_WEATHER_LANGUAGE == 'zh-CHT') {
        //    $scope.weatherL = 'zh_CHT';
        //} else if ($rootScope.language.TIPS_WEATHER_LANGUAGE == 'en') {
        //    $scope.weatherL = 'en';
        //}

        if (configData.language == 'zh_ch') {
            $scope.weatherL = 'zh_CHS';
        } else if (configData.language == 'zh_tw') {
            $scope.weatherL = 'zh_CHT';
        } else if (configData.language == 'en') {
            $scope.weatherL = 'en';
        }

        //进入收银界面 ===================================================
        $scope.goto_cashier = function () {
            if (ShopSetCheck() === 1) {
                return;
            }
            var configData = $api.getStorage('configData');
//            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],msg: configData.start})
            //柜台设置
            if ($rootScope.purviewCheckChange('\/MainCtrl\/cashDeskSet')) {
                $location.path('/cashier/index');
                return;
            }
//            if (GetCustomerInfo('type') == 1) { //lqx 直接显示收银主界面
//                $location.path('/cashier/index');
//                return;
//            }
            if (configData.finished == 1) {
                baison_app.api.confirm({
                    title: $rootScope.language.TIP_CASHIER_TITLE,
                    msg: $rootScope.language.TIP_INDEX_GOTO_CASHIER,
                    buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON, $rootScope.language.ACT_CANCEL]
                }, function (ret, err) {
                    if (ret.buttonIndex == 1) {
                        $scope.startTime();
                    } else if (ret.buttonIndex == 2) {
                        return false;
                    }
                });
//                if (confirm($rootScope.language.TIP_INDEX_GOTO_CASHIER)) {
////                    $location.path('/cashier/start_cashier');
//                    $scope.startTime();
//                }

            } else {
                $location.path('/cashier/index');
            }
        };
        //进入导购界面 ===================================================
        $scope.goto_daogou = function () {
            $location.path('/daogou/index');
        }
        //进入会员界面 ===================================================
        $scope.goto_huiyuan = function () {
            $location.path('/member/list/birthday_member');
        }
        //进入促销界面 ===================================================
        $scope.goto_cuxiao = function () {
            $location.path('/promotion/index');
        }
        //进入订单界面 ===================================================
        $scope.goto_dingdan = function () {
            $location.path('/order/xiaopiao_list/main');
        }
        //进入存货界面 ===================================================
        $scope.goto_cunhuo = function () {
            $location.path('/cunhuo/invoicing_nav');
        }
        //进入分析界面 ===================================================
        $scope.goto_fenxi = function () {
            $location.path('/report/spkc');
        }
        //日结部分=========================================================
        //日结
        $scope.endDay = function () {
            //日结功能显示
//            console.log($rootScope.purview)
//            baison_app.api.alert({msg: $rootScope.purview['\/IndexCtrl\/dayFinished'].show})
//            if ($rootScope.purview['\/IndexCtrl\/dayFinished'].show == 0) {
//                $scope.endDay_info = $rootScope.language.TIPS_MORE;
//                return;
//            } else {
//                $scope.endDay_info = $rootScope.language.TIPS_FINISHED;
//            }
            var nowTime = new Date();
            var i = timeStamp2String(nowTime, 'date');
//            if (configData.start == 0) {
//                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_INDEX_FINISH_WARNING});
//                return;
//            } else {
            if (configData.finished == 0) {
                //判断是否有权限开始营业
                if ($rootScope.purview['\/CashierIndexCtrl\/start_sale'].show == 0) {
                    return;
                }
                baison_app.api.toast({msg: $rootScope.language.TIP_INDEX_GOTO_FINISHED});
                $scope.goto_cashier();
            } else {
                $location.path('/finished/index');
            }
//            };
//            $location.path('/finished/index');
//************************************************************************************
        };
        //    //天气预报 =======================================================
        //    weatherDownload().then(function (ret) {
        //        //有错 result 为undefined
        //        $scope.weather = ret.data.data.result;
        //    }).catch(function (err) {
        //        baison_app.api.toast({
        //            msg: err
        //        });
        //    });
        var sys_type = '';//系统类型 pc 非pc
        try {
            var os = nodeRequire('os');
            switch (os.type()) {
                case "Windows_NT":
                case "Linux":
                case "Darwin":
                    sys_type = 'pc';
            }
        } catch (e) {
            sys_type = '';
        }
        //判断文件类型包文件夹是否存在
        var check_file_exist = function (callback) {
            var fs =  baison_app.fs;
            var path = '';
            if (sys_type == 'pc') {
                path = baison_app.api.fsDir + '\\' + 'barImage';
                fs.exist({
                    path: path
                }, function (ret, err) {
                    if (!ret.exist) {
                        callback(false);
                    } else {
                        callback(true);
                    }
                });
            } else {
                path = 'file://' + baison_app.api.fsDir + '/barImage';
//				baison_app.api.alert({msg:path});
                fs.exist({
                    path: path
                }, function (ret, err) {
                    if (!ret.exist) {
                        callback(false);
                    } else {
                        callback(true);
                    }
                });
            }
        };
 //获取图片地址
        var get_picture_adress = function () {
			delete $scope.barcodes;
			delete $scope.pic;
			check_file_exist(function(ret){
				if(!ret){
					$scope.barcodes = './image/qr_img.jpg';
					$scope.pic = './image/img.jpg';
					return;
				}else{
					if(sys_type == 'pc'){
						$scope.pic = baison_app.api.fsDir + '\\' + 'barImage' + '\\'+'img.jpg';
						$scope.barcodes = baison_app.api.fsDir + '\\' + 'barImage' + '\\'+'qr_img.jpg';
					}else{
						$scope.pic = 'file://' + baison_app.api.fsDir +'/barImage/img.jpg';
						$scope.barcodes ='file://' + baison_app.api.fsDir +'/barImage/qr_img.jpg';
					}
					
				}
			
			});
        };

        get_picture_adress();
        //判断联网状态
        /*
        var connectionType = baison_app.api.connectionType;
        if (connectionType == 'none') {
            //TODO 暂时这么写 测试成功后会删除
            get_picture_adress();
        } else {
            //首页图片=============================================================
            pictureDownload().then(function (ret) {

                if (ret.data.status == 1) {
                    if (typeof ret.data.data.img_url === "undefined") {
                        $scope.pic = ret.data.data.link_url;
                    } else {
                        $scope.pic = ret.data.data.img_url;
                    }
                } else {
                    get_picture_adress();
                }
            }).catch(function (err) {
                baison_app.api.toast({
                    msg: err
                });
            });
            //首页二维码==========================================================
            barcodesDownload().then(function (ret) {
                if (ret.data.status == 1) {
                    if (typeof ret.data.data.img_url === "undefined") {
                        $scope.barcodes = ret.data.data.link_url;
                    } else {
                        $scope.barcodes = ret.data.data.img_url;
                    }
                } else {
                    get_picture_adress();
                }
            }).catch(function (err) {
                baison_app.api.toast({
                    msg: err
                });
            });
        }*/


        //是否有待处理的流程:店铺设置、消息、等等
        $scope.set_curr = $rootScope.current_shop.ShopName ? '' : 'curr';
        //店铺设置
        //$scope.message_curr=$scope.news_select_data.length>0?'curr':'';//历史消息
        //获取图标右上角数字
        //会员右上角数字规则：取会员所属店铺为当前店铺的，今天过生日的会员总人数。如果为0，右上角标示则不显示。需要从服务器获取。
        VIP.get_birthday_num().then(function (ret) {
            if (ret != 0) {
                $scope.huiyuan = ret;
            } else {
                $scope.huiyuan = '';
            }
        }).catch(function (err) {
            baison_app.api.toast({msg: err});
        });
        //收银右上角数字规则：取当前挂单笔数。为0则不显示。从本地数据rootScope获取。
        if (typeof $rootScope.hold_receipt_data == 'undefined') {
            $scope.hold_receipt = '';
        } else {
            var hold_receipt = $rootScope.hold_receipt_data.length;
            if (hold_receipt != 0) {
                $scope.hold_receipt = hold_receipt;
            }
        }
        //存货右上角数字规则：取入库单列表中，待处理的单据数。需要从服务器获取。
        var param = {};
        var curTime = timeStamp2String(new Date(), 'datetime');
        var before_time = new Date().getTime() - 30 * 1000 * 60 * 60 * 24;
        var before = new Date(before_time);
        var beforeTime = timeStamp2String(before, 'datetime');
        param.record_time_start = beforeTime;
        param.record_time_end = curTime;
        param.fOrder = 0;
        var length = 0;
        ruKu.ruku_select(param).then(function (ret) {
            if (typeof ret.data.data == 'undefined' || ret.data.data == '') {
                $scope.cunhuo = '';
                return;
            }
            $.each(ret.data.data, function (i, n) {
                length = length + n.length;
            });
            if (length != 0) {
                $scope.cunhuo = length;
            } else {
                $scope.cunhuo = '';
            }
        }).catch(function (err) {
            baison_app.api.toast({msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET});
        });
        //订单右上角数字规则：取待自提的网络订单数，完成好接口，暂时先隐藏。
        $scope.order = '';
        //首页快捷键部分===========================================================
        //f1收银
        shortCutAction.handler('/index', 'f1', function () {
            $scope.goto_cashier();
            $scope.$apply();
        });
        //f2导购
        shortCutAction.handler('/index', 'f2', function () {
            $scope.goto_daogou();
            $scope.$apply();
        });
        //f3会员
        shortCutAction.handler('/index', 'f3', function () {
            $scope.goto_huiyuan();
            $scope.$apply();
        });
        //f4今日促销
        shortCutAction.handler('/index', 'f4', function () {
            $scope.goto_cuxiao();
            $scope.$apply();
        });
        //f5订单
        shortCutAction.handler('/index', 'f5', function () {
            $scope.goto_dingdan();
            $scope.$apply();
        });
        //f6存货
        shortCutAction.handler('/index', 'f6', function () {
            $scope.goto_cunhuo();
            $scope.$apply();
        });
        //f7分析
        shortCutAction.handler('/index', 'f7', function () {
            $scope.goto_fenxi();
            $scope.$apply();
        });
        //f8日结
        shortCutAction.handler('/index', 'f8', function () {
            //日结TODO
            if ($rootScope.purview['\/IndexCtrl\/dayFinished'].show == 1) {
                $scope.endDay();
                $scope.$apply();
            }
        });
    }];
//导航栏
var NavCtrl = ['$scope', 'ReceiptRecord', 'timeStamp2String',
    function ($scope, ReceiptRecord, timeStamp2String) {
        //获取每日成交笔数  获取本日销售数量（不含退票）
        var nowTime = new Date();
        var param = timeStamp2String(nowTime, 'date');
        ReceiptRecord.get_list_local(param).then(function (ret) {
            $scope.dealNum = 0;
            $scope.dealMoney = 0;
            ret.forEach(function (n) {
                if (n.final_money * 1 > 0) {
                    $scope.dealMoney = n.final_money * 1 + $scope.dealMoney * 1;
                }
                if (n.num * 1 > 0) {
                    $scope.dealNum = 1 + $scope.dealNum * 1;
                }
            });
        });
		ReceiptRecord.get_return_list_local(param).then(function(ret){
            $scope.tNum = 0;
            $scope.tMoney = 0;
            $scope.tNum = Object.keys(ret).length;
            ret.forEach(function (n) {
                $scope.tMoney = n.final_money * 1 + $scope.tMoney * 1;
            });
        });
    }];
//登录控制器 ===========================================================
var LoginCtrl = [
    '$scope', '$rootScope', '$location', 'PosUser', 'AutoPatchList', 'AutoPatchDownload', 'PatchDownload', 'purviewInitial', 'PurviewGet', 'ngDialog', 'get_api', 'shortCutAction','dbDelete_sql','timeStamp2String','dbSelect',
    function (
            $scope, $rootScope, $location, PosUser, AutoPatchList,
            AutoPatchDownload, PatchDownload, purviewInitial, PurviewGet, ngDialog,
            get_api, shortCutAction,dbDelete_sql,timeStamp2String,dbSelect) {
        if (typeof $rootScope.current_shop.ShopName == 'undefined') {
            $rootScope.current_shop.ShopName = $rootScope.language.TIP_INDEX_BIND_SHOP;
        }

        //获取权限
        $rootScope.purviewGetById = function () {
            $rootScope.purview = {};
            purviewInitial('purview').then(function (ret) {
                $rootScope.purview = ret.data;
            }).then(function (ret) {
                PurviewGet.get_purview_by_user($rootScope.user.role_id).then(function (ret) {
                    ret.forEach(function (n) {
                        if ($rootScope.purview[n.url]) {
                            $rootScope.purview[n.url].show = 1;
                        }
                    });
                });
            });
        };
        //默认窗口为main_window，快捷键判断用
        $scope.win_name = 'main_window';
        //商户名
        $scope.shanghu = '';
        //用户列表
        $scope.userlist = [];
        //待登录用户列表, 数据需要从模型获取
        if (typeof $rootScope.current_shop.ShopCode != "undefined") {
            var filter = {
                'UserStatus': 1,
                'ShopCode': $rootScope.current_shop.ShopCode
            };
            PosUser.get_list_all(filter).then(function (ret) {
                ret.forEach(function (n) {
                    if (n.UserPass != '' && n.UserPass != 'undefined') {
                        n.active = "";
                        $scope.userlist.push(n);
                    }
                });
//                $.each(ret, function (i, n) {
//                    $scope.userlist.push({
//                        UserCode: n.UserCode,
//                        UserName: n.UserName,
//                        UserPass: n.UserPass,
//                        UserTel: n.UserTel,
//                        UserManage: n.UserManage,
//                        is_salesman: n.is_salesman,
//                        is_customer: n.is_customer,
//                        is_clerk: n.is_clerk,
//                        is_manage: n.is_manage,
//                        role_id: n.role_id,
//                        active: ""
//                    });
//                });
            });
        }

        //added by lqx maowei on 20170204 在登录页面添加apicloud版本号
        var system_update = function () {
            var appVersion = api.appVersion;
            $("#apiversion").text(appVersion);
        }
        system_update();

        //获取超级管理员密码
        var get_admin_pass = function () {

//            baison_app.api.alert({msg: 111})

            var configData = $api.getStorage('configData');
            if (configData.api_url == '') {
                $scope.userlist.push({UserCode: "000",
                    UserName: "超级管理员",
                    UserPass: configData.adminPass,
                    active: ""});
            } else {
                PurviewGet.check_super_manager_password().then(function (ret) {
					var configData = $api.getStorage('configData');
                    $scope.userlist.push({UserCode: "000",
                        UserName: "超级管理员",
                        UserPass: ret.data.data,
                        active: ""});

                    configData.adminPass = '';
                    $api.setStorage('configData', configData);
                }).catch(function (err) {
//                    $scope.userlist.push({UserCode: "000",
//                        UserName: "超级管理员",
//                        UserPass: configData.adminPass,
//                        active: ""});
                });
            }
        };
        get_admin_pass();

        //当前需要登录的用户
        $scope.login_user = {};
        //当前输入的密码
        $scope.input_password = '';
        //页面动作 =========================================================
        //选择用户动作
        $scope.user_click = function (user) {
            $scope.userlist.forEach(function (o) {
                o.active = "";
                if (user.UserCode == o.UserCode) {
                    o.active = "active";
                }
            });
            $scope.login_user = user;
        };
        //获取是否自动安装
        var get_is_auto_loadinstall = function (patch_list) {

            if (patch_list == undefined || patch_list.length <= 0) {
                return 0;
            }
            for (var i = 0; i < patch_list.length; i++) {
                if (patch_list[i].patch_status != 'TIP_INDEX_FIXED') {
                    //自动下载与安装
                    return 1;
                }
            }
            return 0;
        };
        //跳转进入自动加载与安装
        $scope.progress = false;
        var go_auto_loadinstall = function () {
            if (typeof $rootScope.current_shop.ShopCode != "undefined") {
                AutoPatchList().then(function (response) {
                    var patch_list = response.data.data;
                    if (get_is_auto_loadinstall(patch_list) == 1) {
                        //自动下载与安装
                        launch_auto_load_install();
                    } else {
                        if ($rootScope.user.UserCode == '000') {

                            $location.path('/setting/shop_set');
                        } else {

                            $location.path('/index');
                        }

                    }
                }).catch(function (err) {
                    if (err.data == null) {
                        baison_app.api.toast({msg: $rootScope.language.MSG_NETWORK_ABNORMAL});
                        if ($rootScope.user.UserCode == '000') {

                            $location.path('/setting/shop_set');
                        } else {

                            $location.path('/index');
                        }
                    }
                });
            } else {
                if ($rootScope.user.UserCode == '000') {

                    $location.path('/setting/shop_set');
                } else {

                    $location.path('/index');
                }
            }
        };
        //清除废促销数据
        var clean_rubbish_promotions = function(){
            var _time = timeStamp2String(0, 'datetime');
            var sql = 'select promotion_rule_id from PosPromotionRule where is_audit =0 or is_stop= 1  or  end_time < "' + _time + '"';
            var pid_arr = [];
            dbSelect('YsPos',sql).then(function(ret){
                ret.forEach(function(e){
                    pid_arr.push(e);
                });
                if(pid_arr.length > 0){
                    sql = ' pid in "('+pid_arr+')"';
                    dbDelete_sql('PosPromotionRuleCategory',sql);
                    dbDelete_sql('PosPromotionRuleGift',sql);
                    dbDelete_sql('PosPromotionRuleGoods',sql);
                    dbDelete_sql('PosPromotionRuleOption',sql);
                    dbDelete_sql('PosPromotionRuleRegion',sql);
                    dbDelete_sql('PosPromotionRuleShop',sql);
                    sql = ' where is_audit =0 or is_stop= 1  or  end_time < "' + _time + '"';
                    dbDelete_sql('PosPromotionRule',sql);
                }
            }); 
        };
        //登录动作
        $scope.errorMessage = '';
        $scope.animation_switch = '';
        $scope.do_login = function () {
            if (!$scope.login_user.UserCode) {
                $scope.animation_switch = 'animation';
                setTimeout(function () {
                    $scope.animation_switch = '';
                }, 500)
                $scope.errorMessage = $rootScope.language.TIP_INDEX_SELECT_USER;
                return;
            }
            if ($.md5($scope.input_password) == $scope.login_user.UserPass) {
                //登陆成功
                clean_rubbish_promotions();
                $rootScope.user = $scope.login_user;
                $rootScope.purview = {};
                purviewInitial('purview').then(function (ret) {
                    $rootScope.purview = ret.data;
                }).then(function (ret) {
                    return PurviewGet.get_purview_by_user($rootScope.user.role_id).then(function (ret) {
                        ret.forEach(function (n) {
                            if ($rootScope.purview[n.url]) {
                                $rootScope.purview[n.url].show = 1;
                            }
                        });
                    });
                }).then(function (ret) {
                    if ($rootScope.user.UserCode == '000') {
                        //跳转进入自动加载与安装
                        if (typeof $rootScope.current_shop.ShopCode != "undefined") {
                            //判断是否有自动安装的权限
//                          if ($rootScope.purview['\/index\/loadInstall'].show == '0') {
//                              $location.path('/setting/shop_set');
//                          } else {
//                              go_auto_loadinstall();
//                          }
                            //自动安装
                            go_auto_loadinstall();
//                            $location.path('/setting/shop_set');
                        } else {
                            //不进行自动加载与安装
                            $location.path('/setting/shop_set');
                        }
                    } else {
                        //判断是否有自动安装的权限
                        if ($rootScope.purview['\/index\/loadInstall'].show == '0') {
                            $location.path('/index');
                        } else {
                            //自动安装
                            go_auto_loadinstall();
//                            $location.path('/setting/shop_set');
                        }
                    }

                });
            } else {
                $scope.animation_switch = 'animation'
                setTimeout(function () {
                    $scope.animation_switch = '';
                }, 500);
                $scope.errorMessage = $rootScope.language.TIP_INDEX_PASSWORD;
            }
        };
        /***快捷键部分*************/
        shortCutAction.handler('/login', 'enter', function () {
            if ($scope.win_name == 'main_window') {
                $scope.do_login();
            } else if ($scope.win_name == 'set_shanghu') {
                $scope.$apply();
                //console.log($scope.shanghu);
                $scope.save($scope.shanghu);
            }
            $scope.$apply();
        });
        //F3获取当前焦点到输入框
        shortCutAction.handler('/login', 'f3', function () {
            $scope.focus('txt_pass');
        });
        $scope.select_user = '';
        //上下键选择登录会员
        shortCutAction.handler('/login', 'down', function () {
            if ($scope.select_user === '') {
                $scope.select_user = 0;
            } else if ($scope.select_user < $scope.userlist.length - 1) {
                $scope.select_user++;
            }
            $scope.user_click($scope.userlist[$scope.select_user]);
            $scope.focus('txt_pass');
            $scope.$apply();
        });
        shortCutAction.handler('/login', 'up', function () {
            if ($scope.select_user === '') {
                $scope.select_user = 0;
            } else if ($scope.select_user > 0) {
                $scope.select_user--;
            }
            $scope.user_click($scope.userlist[$scope.select_user]);
            $scope.focus('txt_pass');
            $scope.$apply();
        });
        //自动加载与安装逻辑 start*******************************************
        //自动安装与加载初始化函数

        /**
         $scope.vm = {};
         $scope.vm.value = 0;
         */
        var progressbar = $("#progressbar"), progressLabel = $(".progress-label");
        progressbar.progressbar({
            value: false,
            change: function () {
                progressLabel.text('');
            }
        });
        $scope.loadinfo = {'patch': {}, 'id': 0}; //是否在下载
        $scope.progressTitle = $rootScope.language.TIP_INDEX_DOWNLOAD;
        $scope.install_totalnum = 0;
        //设置进度值
        var set_progress = function () {
            //progressbar.progressbar("value", $scope.vm.value);
        };
        //直接安装进度条
        var go_download_progress = function () {
            /**
             var go_status_timer = setInterval(function () {
             if ($scope.vm.value == 50) {
             clearInterval(go_status_timer);
             return;
             }
             $scope.vm.value += 10;
             set_progress();
             }, 500);
             */
        };
        //获取下载进度
        var get_download_progress = function () {
            var download_status_timer = setInterval(function () {
                AutoPatchDownload.patch_query_status({'patch': $scope.loadinfo.patch, 'id': $scope.loadinfo.id}, function (ret) {
                    //baison_app.api.alert({msg:ret,title:'progress'});
                    var totalSize = ret.totalSize;
                    var finishSize = ret.finishSize;
                    var curdegree = 0;
                    if (totalSize <= finishSize) {
                        curdegree = 100;
                    } else {
                        curdegree = parseInt(finishSize / totalSize) * 100;
                    }
                    curdegree = curdegree >= 100 ? 100 : curdegree;
                    //$scope.vm.value = curdegree;
                    set_progress();
                    if (curdegree == 100) {
                        clearInterval(download_status_timer);
                        $scope.loadinfo.patch.fd_ids = $scope.loadinfo.id;
                        write_down_install_log($scope.loadinfo.patch.patch_code, $scope.loadinfo.id, 'TIP_INDEX_UNFIXED');
                        //安装进度
                        install_progress_logic($scope.loadinfo.patch);
                    }
                });
            }, 500);
        };
        //安装进度
        var install_progress_logic = function (v) {
            $scope.progressTitle = $rootScope.language.TIP_INDEX_FIXING;
            //$scope.vm.value = 50;
            set_progress();
            $scope.cur_install = v.patch_code;
            //安装
            PatchDownload.patch_install(v);
        };
        $rootScope.$on('install_finish', function (event, data) {

            //baison_app.api.alert({msg:"批量完成一个!!!"+data});
            if ($scope.cur_install != data) {
                return;
            }
            $scope.cur_install = '';
            $scope.install_totalnum -= 1;
            $scope.progressCurNum = $scope.install_totalnum;
            //$scope.vm.value = 100;
            set_progress();

            if ($scope.install_totalnum <= 0) {
                $scope.progressTitle = $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED;
                $scope.progress = false;
                AutoPatchList().then(function (response) {
                    var patch_list = response.data.data;
                    if (get_is_auto_loadinstall(patch_list) == 1) {
                        $rootScope.patch_uninstall = true;

                    }
                    if ($rootScope.user.UserCode == '000') {
                        $location.path('/setting/shop_set');
                    } else {
                        $location.path('/index');
                    }
                });
            } else {
                auto_load_install_logic($scope.install_totalnum - 1);
            }
        });
        //下载安装记录
        var write_down_install_log = function (patch_code, id, status) {
            var data = {};
            data['patch_code'] = patch_code;
            data['fd_ids'] = id;
            data['patch_status'] = status;
            AutoPatchDownload.writeback_patchlog(data, $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY, '');
        };
        //自动下载与安装逻辑
        var auto_load_install_logic = function (index) {
            var v = $scope.patch_list[index];
            if (v['patch_status'] != 'TIP_INDEX_FIXED') {
                if (v['patch_status'] != 'TIP_INDEX_UNFIXED') {
                    $scope.progressTitle = $rootScope.language.TIP_INDEX_DOWNLOAD;
                    AutoPatchDownload.patch_download_progress(v, function (ret) {
                        //获取下载进度
                        //baison_app.api.alert({msg:ret,title:'download'});
                        $scope.loadinfo.patch = v;
                        $scope.loadinfo.id = ret.id;
                        if (ret.id <= 0) { //本地已有此包
                            //$scope.vm.value = 100;
                            set_progress();
                            $scope.loadinfo.patch.fd_ids = v.fd_ids;
                            if(ret.id < 0){
                                write_down_install_log($scope.loadinfo.patch.patch_code, $scope.loadinfo.patch.fd_ids, 'TIP_INDEX_NOT_DOWNLOAD');
                            }else{
                                write_down_install_log($scope.loadinfo.patch.patch_code, $scope.loadinfo.patch.fd_ids, 'TIP_INDEX_UNFIXED');
                            }
                            //安装进度
                            install_progress_logic($scope.loadinfo.patch);
                            return;
                        }

                        get_download_progress();
                    });
                } else {
                    //安装进度
                    go_download_progress();
                    install_progress_logic(v);
                }
            } else {
                $scope.install_totalnum -= 1;
                $scope.progressCurNum = $scope.install_totalnum;
                if ($scope.install_totalnum <= 0) {
                    $scope.progressTitle = $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED;
                    var datetime = new Date();
                    endtime = datetime.getTime();
                    var lasttime = endtime - starttime;
                    AutoPatchList().then(function (response) {
                        var patch_list = response.data.data;
                        if (get_is_auto_loadinstall(patch_list) == 1) {
                            $rootScope.patch_uninstall = true;
                        }
                        if ($rootScope.user.UserCode == '000') {
                            $location.path('/setting/shop_set');
                        } else {
                            $location.path('/index');
                        }
                    });
                    //baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],msg:lasttime+'ms',title:'安装时间'});

                    return;
                }
                auto_load_install_logic($scope.install_totalnum - 1);
            }
        };
        //自动下载与安装
        var auto_load_install = function () {
            AutoPatchList().then(function (response) {
                $scope.patch_list = response.data.data;
                var patch_len = $scope.patch_list.length;
                $scope.progressTotalNum = patch_len;
                $scope.progressCurNum = patch_len;
                $scope.install_totalnum = patch_len;
                $rootScope.progressTips = 'Tips!';
                auto_load_install_logic($scope.install_totalnum - 1);
            });
        };
        var starttime = 0;
        var endtime = 0;
        //启动自动安装与更新
        var launch_auto_load_install = function () {
            //自动下载与安装
            var datetime = new Date();
            starttime = datetime.getTime();
            $scope.progress = true;
            auto_load_install();
        };
        //自动加载与安装逻辑 end**********************************************
        //主页或登陆页面点击返回键提示退出程序
        var exitApp = function () {
            baison_app.api.addEventListener({
                name: 'keyback'
            }, function (ret, err) {
                if ($location.$$path == '/index' || $location.$$path == '/login') {
                    baison_app.api.toast({
                        msg: $rootScope.language.TIP_INDEX_EXIT,
                        duration: 2000,
                        location: 'bottom'
                    });
                    baison_app.api.addEventListener({
                        name: 'keyback'
                    }, function (ret, err) {
                        baison_app.api.closeWidget();
                    });
                } else
                    window.history.back();
                setTimeout(function () {
                    exitApp();
                }, 2000)
            });
        };
        exitApp();
        //更新patch状态
        var update_patch_status = function () {
            var data = {};
            data.status = 'TIP_INDEX_NOT_DOWNLOAD';
            AutoPatchDownload.update_patchlog(data, $rootScope.language.TIP_INDEX_DELETE_APP);
        };
        //首次安装根据商户代码获取对应的api地址=============================================
        var windowId = 3;
        var data = $api.getStorage('configData');
        if (data.shanghu == '' || data.api_url == ''||data.shanghu_password==''||data.shanghu_password==undefined) {
            windowId = ngDialog.open({closeByDocument: false,
                trapFocus: false,
                template: './html/set_shanghu.html',
                disableAnimation: true,
                scope: $scope,
                controller: function () {
                    $scope.change_shanghu = function (e) {
                        $scope.shanghu = e;
                    };
                },
                preCloseCallback: function () {
                    $scope.win_name = 'main_window';

                }
            });
            $scope.win_name = 'set_shanghu';
        }
        $scope.save = function (code,password) {
            if (baison_app.api.connectionType == 'none') {
                baison_app.api.toast({msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET});
            } else {
                get_api.get_api(code,password).then(function (res) {
                	//baison_app.api.alert({msg:res,title:'res'});
                
                    if (res.data.status == '1') {
                        var configData = $api.getStorage('configData');
                        configData.api_url = res.data.data.url;
                        configData.shanghu = code;
                        configData.shanghu_password = password;
                        $api.setStorage('configData', configData);
                        baison_app.api.toast({msg: $rootScope.language.TIP_INDEX_SET_SUCCESS});
                        ngDialog.close(windowId);
                        update_patch_status();
                    } else {
                        baison_app.api.toast({msg: $rootScope.language.TIPS_ERROR_CODE_OR_PASSWORD});
                    }
                }).catch(function () {
                    baison_app.api.toast({msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET});
                });
            }

        };
        $scope.cancel = function () {
            ngDialog.close(windowId);
        }
    }];
//进度条控制器
var ProgressBarCtrl = ['$scope', '$rootScope', '$location', 'PosUser', 'AutoPatchList', 'AutoPatchDownload', 'dbSelect',
    function ($scope, $rootScope, $location, PosUser, AutoPatchList, AutoPatchDownload, dbSelect) {

        $scope.vm = {};
        $scope.vm.value = 0;
        var progressbar = $("#progressbar"), progressLabel = $(".progress-label");
        progressbar.progressbar({
            value: false,
            change: function () {
                progressLabel.text(progressbar.progressbar("value") + "%");
            }

        });
        $scope.loadinfo = {'patch': {}, 'id': 0}; //是否在下载
        $scope.progressTitle = $rootScope.language.TIP_INDEX_DOWNLOAD;
        $scope.install_totalnum = 0;
        //设置进度值
        var set_progress = function () {
            progressbar.progressbar("value", $scope.vm.value);
        };
        //直接安装进度条
        var go_download_progress = function () {
            var go_status_timer = setInterval(function () {
                if ($scope.vm.value == 50) {
                    clearInterval(go_status_timer);
                    return;
                }
                $scope.vm.value += 10;
                set_progress();
            }, 500);
        };
        //获取下载进度
        var get_download_progress = function () {
            var download_status_timer = setInterval(function () {

                AutoPatchDownload.patch_query_status({'patch': $scope.loadinfo.patch, 'id': $scope.loadinfo.id}, function (ret) {
                    //baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],msg:ret,title:'rerterere'});
                    var totalSize = ret.totalSize;
                    var finishSize = ret.finishSize;
                    var curdegree = 0;
                    if (totalSize <= finishSize) {
                        curdegree = 100;
                    } else {
                        curdegree = parseInt(finishSize / totalSize) * 100;
                    }
                    curdegree = curdegree >= 100 ? 100 : curdegree;
                    $scope.vm.value = curdegree;
                    set_progress();
                    if (curdegree == 100) {
                        clearInterval(download_status_timer);
                        $scope.loadinfo.patch.fd_ids = $scope.loadinfo.id;
                        write_down_install_log($scope.loadinfo.patch.patch_code, $scope.loadinfo.id, 'TIP_INDEX_UNFIXED');
                        //安装进度
                        //baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],msg:$scope.loadinfo.patch,title:'$scope.loadinfo.patch'});
                        install_progress_logic($scope.loadinfo.patch);
                    }
                });
            }, 500);
        };
        //安装进度
        var install_progress_logic = function (v) {
            $scope.progressTitle = $rootScope.language.TIP_INDEX_FIXING;
            $scope.vm.value = 50;
            set_progress();
            //安装
            AutoPatchDownload.patch_install(v).then(function () {
                $scope.install_totalnum -= 1;
                $scope.progressCurNum = $scope.install_totalnum;
                $scope.vm.value = 100;
                set_progress();
                if ($scope.install_totalnum <= 0) {
                    $scope.progressTitle = $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED;
                    $location.path('/index');
                } else {
                    auto_load_install_logic($scope.install_totalnum - 1);
                }
            });
        };
        //下载安装记录
        var write_down_install_log = function (patch_code, id, status) {
            var data = {};
            data['patch_code'] = patch_code;
            data['fd_ids'] = id;
            data['patch_status'] = status;
            AutoPatchDownload.writeback_patchlog(data, $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY, '');
        };
        //自动下载与安装逻辑
        var auto_load_install_logic = function (index) {
            var v = $scope.patch_list[index];
            if (v['patch_status'] != 'TIP_INDEX_FIXED') {
                if (v['patch_status'] != 'TIP_INDEX_UNFIXED') {
                    $scope.progressTitle = $rootScope.language.TIP_INDEX_DOWNLOAD;
                    AutoPatchDownload.patch_download_progress(v, function (ret) {
                        //获取下载进度
                        $scope.loadinfo.patch = v;
                        $scope.loadinfo.id = ret.id;
                        if (ret.id == 0) { //本地已有此包
                            $scope.vm.value = 100;
                            set_progress();
                            $scope.loadinfo.patch.fd_ids = v.fd_ids;
                            write_down_install_log($scope.loadinfo.patch.patch_code, $scope.loadinfo.patch.fd_ids, 'TIP_INDEX_UNFIXED');
                            //安装进度
                            //baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],msg:$scope.loadinfo.patch,title:'$scope.loadinfo.patch0000'});
                            install_progress_logic($scope.loadinfo.patch);
                            return;
                        }

                        get_download_progress();
                    });
                } else {
                    //安装进度
                    go_download_progress();
                    install_progress_logic(v);
                }
            } else {
                $scope.install_totalnum -= 1;
                $scope.progressCurNum = $scope.install_totalnum;
                if ($scope.install_totalnum <= 0) {
                    $scope.progressTitle = $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED;
                    $location.path('/index');
                    return;
                }
                auto_load_install_logic($scope.install_totalnum - 1);
            }
        };
        //自动下载与安装
        var auto_load_install = function () {
            AutoPatchList().then(function (response) {
                $scope.patch_list = response.data.data;
                var patch_len = $scope.patch_list.length;
                $scope.progressTotalNum = patch_len;
                $scope.progressCurNum = patch_len;
                $scope.install_totalnum = patch_len;
                auto_load_install_logic($scope.install_totalnum - 1);
            });
        };
        if (typeof $rootScope.current_shop.ShopCode != "undefined") {
            //自动下载与安装
            auto_load_install();
        }


    }];
MainCtrl.$injector = ['$route','$rootScope', '$scope', '$location', '$window', '$interval', 'messageGet', 'messageRead', 'saveUserReadMessage', 'BaseGoods', 'ngDialog', 'ReceiptRecord', 'Language', 'shopCashDesk', 'ShopSetCheck', 'timeStamp2String', 'shortCutAction', 'ShopAttend','ThirdDev','waitUpLoad'];
HelloCtrl.$injector = ['$interval', '$rootScope', '$location', 'dbOpen', 'dbInit', 'dbVesionInit', 'appInit', 'AutoPatchDownload'];
IndexCtrl.$injector = ['$scope', '$rootScope', '$location', 'UserLoginCheck', 'UserSetPicture', 'weatherDownload', 'pictureDownload', 'barcodesDownload', 'apiService', 'timeStamp2String', 'VIP', 'ruKu', 'ngDialog', 'get_api', 'shortCutAction', 'ShopSetCheck', 'checkGetList'];
NavCtrl.$injector = ['$scope', 'ReceiptRecord', 'timeStamp2String'];
LoginCtrl.$injector = ['$scope', '$rootScope', '$location', 'PosUser', 'AutoPatchList', 'AutoPatchDownload', 'PatchDownload', 'purviewInitial', 'PurviewGet', 'ngDialog', 'get_api', 'shortCutAction'];
ProgressBarCtrl.$injector = ['$scope', '$rootScope', '$location', 'PosUser', 'AutoPatchList', 'AutoPatchDownload', 'dbSelect'];